package com.frogs.ucenter.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.frogs.framework.util.StringUtil;

/**
 * 数字签名工具类
 */
public class SignVerifyUtil {
	
	private static final Logger log = LoggerFactory.getLogger(SignVerifyUtil.class);
	
	/**
	 * 验证参数的签名是否正确
	 * 
	 * @param params 参数集合
	 * @param sign 签名字符串
	 * @return 签名正确返回true,否则返回false
	 */
	public static boolean verifySign(Map<String, String> params, String key) {
		
		if(params != null) {
			return sign(params, key).equalsIgnoreCase(params.get("sign"));
		}
		
		return false;
	}
	
	public static String sign(Map<String, String> params, String key) {
		String preStr = createLinkString(paraFilter(params));
		return StringUtil.md5(preStr + key);
	}
	
	/** 
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params) {

        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        StringBuffer preStr = new StringBuffer();

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);

            if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
            	preStr.append(key).append("=").append(value);
            } else {
            	preStr.append(key).append("=").append(value).append("&");
            }
        }

		return preStr.toString();
    }
    
    /** 
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params, boolean encode) {

        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        StringBuffer preStr = new StringBuffer();
        
        try {
			for (int i = 0; i < keys.size(); i++) {
			    String key = keys.get(i);
			    String value = params.get(key);

			    if(value == null) {
			    	continue;
			    }
			    
			    if (i == keys.size() - 1) {//拼接时，不包括最后一个&字符
			    	preStr.append(key).append("=").append(encode ? URLEncoder.encode(value, "UTF-8") : value);
			    } else {
			    	preStr.append(key).append("=").append(encode ? URLEncoder.encode(value, "UTF-8") : value).append("&");
			    }
			}
		} catch (UnsupportedEncodingException e) {
			log.error("func[createLinkString] params[{}] encode[{}] exception[{} - {}] desc[fail]",//
					new Object[] { params.toString(), encode, e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		}

		return preStr.toString();
    }
    
    
    /** 
     * 除去数组中的空值和签名参数
     * @param sArray 签名参数组
     * @return 去掉空值与签名参数后的新签名参数组
     */
    public static Map<String, String> paraFilter(Map<String, String> sArray) {

        Map<String, String> result = new HashMap<String, String>();

        if (sArray == null || sArray.size() <= 0) {
            return result;
        }

        for (String key : sArray.keySet()) {
            String value = sArray.get(key);
            if (value == null || value.equals("") || key.equalsIgnoreCase("sign") || key.equalsIgnoreCase("queryString")) {
                continue;
            }
            result.put(key, value);
        }

        return result;
    }
    
	public static Map<String, String> getParams(Map<String, Object> parameterMap, String queryString) {
    	//获取支付宝POST过来反馈信息
    	Map<String,String> params = new HashMap<String,String>();
    	for (Iterator<String> iter = parameterMap.keySet().iterator(); iter.hasNext();) {
    		String name = (String) iter.next();
    		String[] values = (String[]) parameterMap.get(name);
    		String valueStr = "";
    		for (int i = 0; i < values.length; i++) {
    			valueStr = (i == values.length - 1) ? valueStr + values[i]
    					: valueStr + values[i] + ",";
    		}
    		//乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "UTF-8");
    		params.put(name, valueStr);
    	}
    	
    	params.put("queryString", queryString);
    	
    	return params;
    }
	
	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		
		list.add("amount");
		list.add("channel");
		list.add("orderNo");
		list.add("ordDesc");
		list.add("partner");
		list.add("productName");
		
		Collections.sort(list);
		
		
		
		String md5 = StringUtil.md5("amount=0.02&channel=alipay&orderNo=O12110700855&ordDesc=康桥温泉、北峰山漂流二天自驾游（仅供测试之用231）&partner=201211061638&productName=康桥温泉、北峰山漂流二天自驾游（仅供测试之用231）17bc6065-a21f-44b6-857d-780f7d06e613");
		System.out.println(md5);
	}
}
